package com.aube;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.utils.ForceLoginHelper;
import com.huyn.baseframework.dynamicload.CanCloseLayout;
import com.huyn.baseframework.model.WXLoginModel;
import com.huyn.baseframework.share.QQUtil;
import com.huyn.baseframework.share.WeiboConstants;
import com.huyn.baseframework.share.WeiboUtil;
import com.huyn.baseframework.share.WxUtil;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UserUtil;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huyaonan on 16/6/13.
 */
public class BaseFragmentActivity extends FragmentActivity {

    protected final String TAG = getClass().getSimpleName();

    private List<CanCloseLayout> mCanCloseLayoutGroup;

    private ForceLoginHelper mLoginHelper;

    private AuthInfo mAuthInfo;
    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 快速授权时，请不要传入 SCOPE，否则可能会授权不成功
        mAuthInfo = new AuthInfo(this, WeiboConstants.APP_KEY, WeiboConstants.REDIRECT_URL, WeiboConstants.SCOPE);
        mSsoHandler = new SsoHandler(this, mAuthInfo);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void reportUmengEvent(String id, String value) {
        if(StringUtils.isNotBlank(value))
            MobclickAgent.onEvent(this, id, value);
        else
            MobclickAgent.onEvent(this, id);
    }

    public void reportUmengEvent(String id) {
        MobclickAgent.onEvent(this, id);
    }

    /**
     * weibo:1
     * weixin:2
     * @param channel
     */
    public void doLogin(int channel) {
        switch (channel) {
            case 1:
                weiboLogin();
                break;
            case 2:
                WxUtil.wxLoginRequest(this);
                break;
        }
    }

    public void weiboLogin() {
        WeiboUtil.getInstance(this).authorize(this, mSsoHandler, new Response.Listener<WXLoginModel>() {
            @Override
            public void onResponse(WXLoginModel response) {
                if(response != null && response.success()) {
                    UserUtil.saveInstance(BaseFragmentActivity.this, response.data);
                    sendBroadcast(new Intent(UserUtil.LOGIN_SUCCESS));
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }

            @Override
            public void onStart() {

            }
        });
    }

    public View getBaseRootView() {
        return null;
    }

    public void showLoginLayout() {
        if(getBaseRootView() == null)
            return;
        if(mLoginHelper == null)
            mLoginHelper = new ForceLoginHelper(this);

        mLoginHelper.showLoginLayout();
    }

    public boolean dismissLoginHelper() {
        if(mLoginHelper != null)
            return mLoginHelper.dismissLayout();
        return false;
    }

    public static String appendLabels(String... value) {
        if(value == null || value.length == 0)
            return "";
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<value.length; i++) {
            sb.append(value[i]);
            if(i != value.length-1)
                sb.append(",");
        }
        return new String(sb);
    }

    public void registToGroup(CanCloseLayout layout) {
        if(layout == null)
            return;
        if(mCanCloseLayoutGroup == null)
            mCanCloseLayoutGroup = new ArrayList<>();
        mCanCloseLayoutGroup.add(layout);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCodeBackPressed(keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }

    public boolean keyCodeBackPressed(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(dismissLoginHelper())
                return true;
            if(mCanCloseLayoutGroup != null) {
                for(CanCloseLayout layout : mCanCloseLayoutGroup) {
                    if(layout.onKeyDownEvent(keyCode, event))
                        return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode,resultCode,data, QQUtil.getInstance(this).getBaseUiListener());
        }
        // 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResult
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
